﻿using ORM.Model;
using ORM.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ORM.Parser.Design
{
    /// <summary>
    /// 插入语句反向解析目前存在的局限性，不支持解析一条语句插入多条，只能支持单条数据插入，且主键如果不在语句中赋值或者是自增长ID，也会存在问题
    /// </summary>
    public class InsertStatement : BaseStatement
    {
        public string PKValue { set; get; }
        public override void Parse(string SQLText)
        {
            base.Parse(SQLText);
            int insertindex = this.SQLText.IndexOf("into\n");
            this.TableName = this.SQLText.Substring(insertindex + 6, this.SQLText.Length - insertindex - 6).Trim().Split(new char[] { '(' }, StringSplitOptions.RemoveEmptyEntries)[0].Trim();
            string columnstr = this.SQLText.Replace("insert", string.Empty).Replace("into\n", string.Empty).Replace(TableName + "\n", string.Empty);
            int valuesindex = columnstr.IndexOf("values\n");
            string columndefinestr = columnstr.Substring(0, valuesindex).Trim().Replace("(", string.Empty).Replace(")", string.Empty);
            string columnvaluestr = columnstr.Substring(valuesindex + 8, columnstr.Length - valuesindex - 8).Trim().Replace("(", string.Empty).Replace(")", string.Empty);
            string[] columndefinearray = columndefinestr.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            string[] columvaluearray = columnvaluestr.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            PKName = MapperBuilder.GetInstance().GetSchemaTableKeyFieldName(ConnectStringName, TableName).ToLower();
            PKValue = columvaluearray[Array.IndexOf(columndefinearray, PKName)].Replace("'",string.Empty);
        }
        public override List<string> GetRollBackSQL()
        {
            this.RollBackSQLTextList.Add(string.Format("delete from {0} where {1}='{2}'", TableName, PKName, PKValue));
            return base.GetRollBackSQL();
        }
    }
}
